package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {

    @Autowired
    private StrategyDetailMapper strategyDetailMapper;

    @Autowired
    private StrategyContentMapper strategyContentMapper;

    public void saveOrUpdate(StrategyDetail entity) {
        if(entity.getSequence() == null){
            // 用户没有填序号，可以自动生成
            // 先查询当前攻略中最大序号
            Integer sequence = strategyDetailMapper
                    .selectMaxSequenceByCatalogId(entity.getCatalog().getId());
            // 增加
            if(sequence == null){
                sequence = 0;
            }
            entity.setSequence(sequence + 1);

        }
        // 设置发布时间
        if(entity.getState() == StrategyDetail.STATE_RELEASE){
            entity.setReleaseTime(new Date());
        }
        // 文章内容的主键关联
        StrategyContent strategyContent = entity.getStrategyContent();

        if (entity.getId() == null) {
            // 增加
            /// 设置创建时间
            entity.setCreateTime(new Date());
            strategyDetailMapper.insert(entity);
            // 文章内容关联
            strategyContent.setId(entity.getId());
            strategyContentMapper.insert(strategyContent);
        } else {
            // 修改
            strategyDetailMapper.updateByPrimaryKey(entity);
            // 文章内容关联
            strategyContent.setId(entity.getId());
            strategyContentMapper.updateByPrimaryKey(strategyContent);
        }
    }



    public PageInfo<StrategyDetail> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo<>(list);

    }

    // 根据攻略id获取内容
    public String getContentById(Long id) {
        return strategyContentMapper.selectByPrimaryKey(id).getContent();
    }

    public StrategyDetail get(Long id) {
        // 1查询文章的基本信息
        StrategyDetail strategyDetail = strategyDetailMapper.selectByPrimaryKey(id);
        // 2查询文章的内容
        StrategyContent strategyContent = strategyContentMapper.selectByPrimaryKey(id);
        strategyDetail.setStrategyContent(strategyContent);
        return strategyDetail;
    }

    public int selectStragyByCatalogId(Long catalogId) {
        return strategyDetailMapper.selectStragyByCatalogId(catalogId);
    }
}
